﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dotnet.FormExtensions.UsrControl
{
    partial class UcDataGridViewPage
    {
        private void cmbPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtKw.Text))
            {
                BindSource(this._dataTable);
            }
            else
            {
                BindSource(this._dataTableSearch);
            }
        }
        private void txtPageControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                _pagesize = Int32.Parse(txtPageSize.Text);
                _pagecount = (int)Math.Ceiling(_dataTable.Rows.Count * 1.0 / _pagesize); //页面数
                _currentpage = 1;
                SetPageControlState(_pagecount,_currentpage);
                if (string.IsNullOrEmpty(txtKw.Text))
                {
                    //SetBindPageData(this._dataTable, _pagesize);
                }
                else
                {
                    // SetBindPageData(this._dataTableSearch, _pagesize);
                }
            }
        }

        private void txtKw_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtKw.Text) && string.IsNullOrEmpty(TextChangeState))
            {
                //dgvMain.DataSource = _dataTable;
                //this.DataTable = _dataTable; //对dgvMain.DataSource赋值都走属性DataTable的方式。
                return;
            }
        }
        private void cmbCondition_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txtKw.Focus();
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.C | Keys.Control:
                    if (!string.IsNullOrEmpty(_cellValue))
                    {
                        Clipboard.SetText(_cellValue);
                        //FrmOutput.OutputLog.Post(new ActionBlockPostEvengArgs() { LogType = LogType.Info, Info = $"复制【{_cellValue}】到剪粘板" });
                    }
                    break;
                case Keys.F5: RefreshDgvMain(); break;
                case Keys.F6: RefreshDb(); break;
            }
            return base.ProcessDialogKey(keyData);
        }

        private void btnPageChang_Click(object sender, EventArgs e)
        {
            ToolStripButton tsbtn = sender as ToolStripButton;
            if (tsbtn == null) throw new Exception("ToolStripButton转换为空");
            string txt = tsbtn.Text;
            switch (txt)
            {
                case "移到下一条记录": _currentpage++; break;
                case "移到上一条记录": _currentpage--; break;
                case "移到最后一条记录": _currentpage = _pagecount; break;
                case "移到第一条记录": _currentpage = 1; break;
            }
            SetPageControlState(_pagecount, _currentpage);
            //this.cmbPage.SelectedIndex = _currentpage;
        }

        StringBuilder sb = new StringBuilder();
        private void dgvMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            txtKw.Focus();
            //string colName = dgvMain.CurrentCell?.OwningColumn.Name;

            //if (chkColumns.Checked == true)
            //{
            //    if (!_dictColumns.ContainsKey(colName))
            //    {
            //        _dictColumns.Add(colName, "");
            //        sb.Append(colName).Append(",");
            //    }    
            //    txtColName.AutoSetTextWidth(sb.ToString().TrimEnd(','));
            //}
            //else
            //{
            //    txtColName.AutoSetTextWidth(colName);
            //    this._cellValue = (dgvMain.CurrentCell.Value == DBNull.Value || dgvMain.CurrentCell.Value == null) ? "" : 
            //        dgvMain.CurrentCell.Value.ToString();
            //}
        }
        private Dictionary<string, string> GetMultiColValue(List<string> list)
        {
            Dictionary<string, string> dictColValue = new Dictionary<string, string>();
            if (_dictColumns.Count > 0)
            {
                int i = 0;
                foreach (KeyValuePair<string, string> kp in _dictColumns)
                {
                    if (i < list.Count)
                    {
                        dictColValue.Add(kp.Key, list[i]);
                        i++;
                    }
                }
            }
            return dictColValue;
        }
        private void txtKw_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                List<DataRow> temp = new List<DataRow>();
                List<string> listIn = txtKw.Text.Split(',').ToList();
                Dictionary<string, string> dictColValue = GetMultiColValue(listIn);

                if (cmbCondition.Text.Contains("包含"))
                {
                    if (dictColValue.Count > 0)  //多个字段组合查询
                    {
                        DataTable dt = _dataTable.Copy();
                        foreach (KeyValuePair<string, string> kp in dictColValue)
                        {
                            temp = (from tb in dt.AsEnumerable()
                                    where (tb.Field<object>(kp.Key) == null ? "" : tb.Field<object>(kp.Key).ToString().ToLower()).Contains(kp.Value)
                                    select tb).ToList<DataRow>();
                            dt = temp.CopyToDataTable();
                        }
                    }
                    else
                    {
                        temp = (from tb in _dataTable.AsEnumerable()
                                from kw in listIn
                                where (tb.Field<object>(txtColName.Text) == null ? "" : tb.Field<object>(txtColName.Text).ToString().ToLower()).Contains(kw.ToLower())
                                select tb).ToList<DataRow>();
                    }
                }
                else if (cmbCondition.Text.Contains("开头"))
                {
                    if (dictColValue.Count > 0)  //多个字段组合查询
                    {
                        DataTable dt = _dataTable.Copy();
                        foreach (KeyValuePair<string, string> kp in dictColValue)
                        {
                            temp = (from tb in dt.AsEnumerable()
                                    where (tb.Field<object>(kp.Key) == null ? "" : tb.Field<object>(kp.Key).ToString().ToLower()).StartsWith(kp.Value)
                                    select tb).ToList<DataRow>();
                            dt = temp.CopyToDataTable();
                        }
                    }
                    else
                    {
                        temp = (from tb in _dataTable.AsEnumerable()
                                from kw in listIn
                                where (tb.Field<object>(txtColName.Text) == null ? "" : tb.Field<object>(txtColName.Text).ToString().ToLower()).StartsWith(kw.ToLower())
                                select tb).ToList<DataRow>();
                    }
                }
                else if (cmbCondition.Text.Contains("结尾"))
                {
                    if (dictColValue.Count > 0)  //多个字段组合查询
                    {
                        DataTable dt = _dataTable.Copy();
                        foreach (KeyValuePair<string, string> kp in dictColValue)
                        {
                            temp = (from tb in dt.AsEnumerable()
                                    where (tb.Field<object>(kp.Key) == null ? "" : tb.Field<object>(kp.Key).ToString().ToLower()).EndsWith(kp.Value)
                                    select tb).ToList<DataRow>();
                            dt = temp.CopyToDataTable();
                        }
                    }
                    else
                    {
                        temp = (from tb in _dataTable.AsEnumerable()
                                from kw in listIn
                                where (tb.Field<object>(txtColName.Text) == null ? "" : tb.Field<object>(txtColName.Text).ToString().ToLower()).EndsWith(kw.ToLower())
                                select tb).ToList<DataRow>();
                    }
                }
                else if (cmbCondition.Text.Contains("相等"))
                {
                    if (dictColValue.Count > 0)  //多个字段组合查询
                    {
                        DataTable dt = _dataTable.Copy();
                        foreach (KeyValuePair<string, string> kp in dictColValue)
                        {
                            temp = (from tb in dt.AsEnumerable()
                                    where (tb.Field<object>(kp.Key) == null ? "" : tb.Field<object>(kp.Key).ToString().ToLower()).Equals(kp.Value)
                                    select tb).ToList<DataRow>();
                            dt = temp.CopyToDataTable();
                        }
                    }
                    else
                    {
                        temp = (from tb in _dataTable.AsEnumerable()
                                from kw in listIn
                                where (tb.Field<object>(txtColName.Text) == null ? "" : tb.Field<object>(txtColName.Text).ToString().ToLower()).Equals(kw.ToLower())
                                select tb).ToList<DataRow>();
                    }
                }
                else { }
                /////////////////
                var rows = temp.Distinct<DataRow>();
                if (rows.Count() == 0)
                {
                    // dgvMain.DataSource = null;
                    this.DataTableSearch = _dataTable.Clone();
                    return;
                }
                this.DataTableSearch = rows.CopyToDataTable();
            }
        }
    }
}
